package com.spd.singlechipupgrade;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.serialport.DeviceControlSpd;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.spd.singlechipupgrade.utils.Upgrade;
import com.speedata.libutils.DataConversionUtils;

import java.util.Arrays;

import me.f1reking.serialportlib.SerialPortHelper;
import me.f1reking.serialportlib.listener.ISerialPortDataListener;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button mUpgrade, mUp, mDown, mRead;

    TextView message;

    DeviceControlSpd deviceControl;

    SerialPortHelper mSerialPortHelper1;

    @SuppressLint("HandlerLeak")
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initHandler();


    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {

        super.onPause();
    }


    private void initHandler() {
        handler = new Handler(Looper.getMainLooper()) {
            @SuppressLint({"SetTextI18n", "HandlerLeak"})
            @Override
            public void handleMessage(Message msg) {

            }
        };
    }


    private void initSerial() {
        if (mSerialPortHelper1 == null) {

            mSerialPortHelper1 = new SerialPortHelper();

            try {
                mSerialPortHelper1.setPort("/dev/ttysWK1");
                mSerialPortHelper1.setBaudRate(115200);
                mSerialPortHelper1.setDataBits(8);
                mSerialPortHelper1.setStopBits(2);
                mSerialPortHelper1.open();
            } catch (Exception e) {
                e.printStackTrace();
            }

            App.getInstance().setSerialPortHelper(mSerialPortHelper1);

            initSerialPort1();

        }
    }

    private void initSerialPort1() {
        if (mSerialPortHelper1 != null) {
            mSerialPortHelper1.setISerialPortDataListener(new ISerialPortDataListener() {
                @Override
                public void onDataReceived(byte[] bytes) {
                    if (bytes != null) {
                        Log.d("RECE", DataConversionUtils.byteArrayToString(bytes));

                        Message msg = new Message();

                        msg.obj = bytes;

                        byte[] temp = (byte[]) msg.obj;
                        System.out.println(Arrays.toString(temp));

                        String string = DataConversionUtils.byteArrayToString(temp);

                        if (string == null || "".equals(string.trim())) {
                            return;
                        }
                        Upgrade.setStr(string);

                        runOnUiThread(() -> {

                            if ((System.currentTimeMillis() - mkeyTime) > s) {
                                mkeyTime = System.currentTimeMillis();
                                message.setText(Upgrade.getStrMsg());// 更新消息文本视图
                            }
                        });


                    }

                }

                @Override
                public void onDataSend(byte[] bytes) {

                }
            });
        }

    }

    private long mkeyTime = 0;
    int s = 1000;

    private void initGpios() {

        try {
            //GPIO路径
            deviceControl = new DeviceControlSpd(DeviceControlSpd.POWER_NEWMAIN_FG);
            deviceControl.newFgSetGpioOn(55);
            deviceControl.newFgSetGpioOff(56);
            Thread.sleep(500);
            deviceControl.newFgSetGpioOn(56);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //开串口
        initSerial();
    }


    private void initView() {
        mUpgrade = findViewById(R.id.upgrade);
        mUpgrade.setOnClickListener(this);

        mUp = findViewById(R.id.up);
        mUp.setOnClickListener(this);

        mDown = findViewById(R.id.down);
        mDown.setOnClickListener(this);

        message = findViewById(R.id.message);

        mRead = findViewById(R.id.read);
        mRead.setOnClickListener(this);

    }

    private Thread upgradeThread; // 添加一个成员变量来保存写入操作的线程

    @Override
    public void onClick(View v) {
        if (v == mUpgrade) {

            upgradeThread = new Thread(() -> {
                try {
                    Upgrade.runWriteBin();

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            upgradeThread.start();

        } else if (v == mUp) {
            initGpios();
        } else if (v == mDown) {
            releaseGpios();
        } else if (v == mRead) {
            message.setText(Upgrade.getStrMsg());// 更新消息文本视图
        }
    }


    @Override
    protected void onDestroy() {

        super.onDestroy();
    }

    private void releaseGpios() {
        //关串口
        if (mSerialPortHelper1 != null) {
            mSerialPortHelper1.close();
        }
        mSerialPortHelper1 = null;

        try {
            //GPIO路径
            deviceControl = new DeviceControlSpd(DeviceControlSpd.POWER_NEWMAIN_FG);
            deviceControl.newFgSetGpioOff(55);
            deviceControl.newFgSetGpioOff(56);
            Thread.sleep(500);
            deviceControl.newFgSetGpioOn(56);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}